﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using WinTime.Data;
using WinTime.Data.Entity;
using WinTime.Models;

namespace WinTime.ViewModels;
public class CategoryViewModel : ObservableRecipient
{
    private readonly IMapper _mapper;

    public CategoryDto SelectedCategory
    {
        get; set;
    }

    public ObservableCollection<CategoryDto> CategoryList
    {
        get; private set;
    }

    public CategoryViewModel()
    {
        _mapper = App.GetService<IMapper>();
        SelectedCategory = new();
        CategoryList = new();
        ListCategories();
    }

    public void ListCategories()
    {
        CategoryList.Clear();
        using var context = new ApplicationDbContext();
        var list = _mapper.Map<List<CategoryDto>>(context.CategoryModels.ToList());
        foreach (var item in list)
        {
            CategoryList.Add(item);
        }
    }

    public void ListReload(CategoryModel newCategory)
    {
        var newDto = _mapper.Map<CategoryDto>(newCategory);
        if (newCategory.ID > 0)
        {
            CategoryList.Remove(SelectedCategory);
        }
        CategoryList.Add(newDto);
    }

    public void AddCategory(CategoryModel category)
    {
        using var context = new ApplicationDbContext();
        context.Add(category);
        context.SaveChanges();
    }

    public void UpdateCategory(CategoryModel category)
    {
        using var context = new ApplicationDbContext();
        context.Update(category);
        context.SaveChanges();
    }

    public void DeleteCategory(int id)
    {
        using var context = new ApplicationDbContext();
        var deleteModel = context.Find<CategoryModel>(id);
        if (deleteModel != null)
        {
            context.CategoryModels.Remove(deleteModel);
            context.SaveChanges();
        }
    }

    public CategoryModel? FindCategory(int id)
    {
        using var context = new ApplicationDbContext();
        var model = context.Find<CategoryModel>(id);
        return model;
    }
}
